<?php

/** Handles all user interactions
**@author Ilmi Ali
*/
include_once "class.mailbase.php";

class GenericUser
{

/**
     * The database object
     *
     * @var object
     */
    private $_db;

    /**
     * Checks for a database object and creates one if none is found
     *
     * @param object $db
     * @return void
     */
    public function __construct($db=NULL)
    {
        if(is_object($db))
        {
            $this->_db = $db;
        }
        else
        {
            $dsn = "mysql:host=".DB_HOST.";dbname=".DB_NAME;
            $this->_db = new PDO($dsn, DB_USER, DB_PASS);
        }
    }
	
	public function createAccount()
    {
		$e = trim($_POST['email']);
		$p = trim($_POST['password']);
        $v = sha1(time());

        $sql = "SELECT COUNT(Useremail) AS theCount
                FROM users
                WHERE Useremail=:email";
        if($stmt = $this->_db->prepare($sql)) {
            $stmt->bindParam(":email", $e, PDO::PARAM_STR);
            $stmt->execute();
            $row = $stmt->fetch();
            if($row['theCount']!=0) {
                return '<article id="signup_container">
		<form method="post" action="signup.php" id="signup">
			<h1>Sorry! The email is already in use, please try another one.</h1>
			<input type="username" placeholder="User Name" required="" name = "username">
			<input type="email" placeholder="Email" required="" name = "email">
			<input type="password" placeholder="Choose your password" required="" name = "password">
			<input type="password" placeholder="Confirm password" required="">					
			<button type="submit">Sign up</button>	
		</form>
            	
               
    </article>';;
            }
			}
				
            if(!$this->sendVerificationEmail($e, $v)) {
                return ' <article id="signup_container">
		<div id="signup">
			<h1> There was an error sending your verification email. Please try again later.</h1>
		</div>       
    </article>';
            }
            $stmt->closeCursor();
        
		
		$sql = "INSERT INTO users(UserEmail, Password, ver_code)
                VALUES(:email, MD5(:pass), :ver)";
        if($stmt = $this->_db->prepare($sql)) {
            $stmt->bindParam(":ver", $v, PDO::PARAM_STR);
			$stmt->bindParam(":email", $e, PDO::PARAM_STR);
            $stmt->bindParam(":pass", $p, PDO::PARAM_STR);
            $stmt->execute();
            $stmt->closeCursor();

            $userID = $this->_db->lastInsertId();
            $url = dechex($userID);
		} else {
            return ' <article id="signup_container">
		<div id="signup">
			<h1> An Error occured! Please try again later.</h1>
		</div>       
    </article>';
        }
		
		return ' <article id="signup_container">
		<div id="signup">
			<h1> Almost there! We sent a verification mail to your email, plase follow the link to complete registeration!</h1>
		</div>       
    </article>';
	}
	
	/**
     * Sends an email to a user with a link to verify their new account
     *
     * @param string $email    The user's email address
     * @param string $ver    The random verification code for the user
     * @return boolean        TRUE on successful send and FALSE on failure
     */
	
	private function sendVerificationEmail($email, $ver)
    {
		$mail = new MailBase(); 
        $e = sha1($email); // For verification purposes
        $to = trim($email);

        $subject = "[Colored Lists] Please Verify Your Account";

        $headers = <<<MESSAGE
		From: ComicBlocks <donotreply@comicblocks.com>
	Content-Type: text/plain;
MESSAGE;

        $msg = <<<EMAIL
You have a new account at ComicBlocks!

To get started, please activate your account by following the link below.

Activate your account: http://localhost/main/account_setup.php?v=$ver&e=$e

If you have any questions, please contact help@comicblocks.com.

--
Thanks!

www.comicblocks.com
EMAIL;
		$mail->sendMail($to, "New User", $headers, $msg);
		return true;
    }
	
	/**
     * Checks credentials and verifies a user account
     *
     * @return array    an array containing a status code and status message
     */
    public function verifyAccount()
    {
        $sql = "SELECT UserEmail
                FROM users
                WHERE ver_code=:ver
                AND SHA1(Useremail)=:email
                AND verified=0";

        if($stmt = $this->_db->prepare($sql))
        {
            $stmt->bindParam(':ver', $_GET['v'], PDO::PARAM_STR);
            $stmt->bindParam(':email', $_GET['e'], PDO::PARAM_STR);
            $stmt->execute();
            $row = $stmt->fetch();
            if(isset($row['UserEmail']))
            {
                // Logs the user in if verification is successful
                $_SESSION['Username'] = $row['UserEmail'];
                $_SESSION['LoggedIn'] = 1;
            }
            else
            {
                return array(4, '<h2>Verification Error</h2>n"
                    . "<p>This account has already been verified. "
                    . "Did you <a href="/password.php">forget "
                    . "your password?</a>');
            }
			$sql = "UPDATE users
                    SET verified=1
                    WHERE ver_code=:ver
                    LIMIT 1";
            try
            {
                $stmt = $this->_db->prepare($sql);
                $stmt->bindParam(":ver", $_GET['v'], PDO::PARAM_STR);
                $stmt->execute();
				
                
            }
            catch(PDOException $e)
            {
                 return array(4, '<h2>Verification Error, please try again later.</h2>');
            }
            $stmt->closeCursor();

            // No error message is required if verification is successful
            return array(0, $_GET['e']);
        }
        else
        {
            return array(2, "<h2>Error</h2>n<p>Database error.</p>");
        }
    }
	
	
	/**Create profile method**/
	
	public function createProfile() {
		
		
		$f = $_POST['firstname'];
		$l = $_POST['lastname'];
		$v = $_POST['v'];
		
		$sql = "SELECT UserID from users
				WHERE ver_code =:ver
				LIMIT 1";
				
			//Create unique username and directories and create a user thumb.
		try {
				$stmt = $this->_db->prepare($sql);
				$stmt->bindParam(":ver", $v, PDO::PARAM_STR);
				$stmt->execute();
				$row = $stmt->fetch();
				if(isset($row['UserID'])) {
					$u = $f. '.' .$l. '.'.$row['UserID'];
					$u = strtolower($u);
					$user_dir = "../dir/users/".$u;
					mkdir($user_dir,0755);
					$thumb_dir = $user_dir."/user_thumb/";
					mkdir($thumb_dir,0755);
					$blocks_dir = $user_dir."/blocks/";
					mkdir($blocks_dir,0755);
					$image = $this->uploadImageFile($thumb_dir, $u);
					
				}
				
				else
					 return "User ID not found";
			
			}
			catch(PDOException $e)
			{
                return "Failed with retrieval of user information";
			}
	
		$sql = "UPDATE users
				SET FirstName =:firstname, LastName =:lastname, UserThumb =:image, UserName =:user, user_dir =:dir
				WHERE ver_code =:ver
				LIMIT 1";
				
		try {
			
			$stmt = $this->_db->prepare($sql);
			$stmt->bindParam(":ver", $v, PDO::PARAM_STR);
			$stmt->bindParam(":firstname", $f, PDO::PARAM_STR);
			$stmt->bindParam(":lastname", $l, PDO::PARAM_STR);
			$stmt->bindParam(":image", $image, PDO::PARAM_STR);
			$stmt->bindParam(":user", $u, PDO::PARAM_STR);
			$stmt->bindParam(":dir", $user_dir, PDO::PARAM_STR);
			$stmt->execute();
			$stmt->closeCursor();
			
			return "Success!!";
		}
		
		 catch(PDOException $e)
         {
                return "FAIL!!";
         }
		
			
	
	}
	
	
	
	private function uploadImageFile($thumb_dir, $u) { // Note: GD library is required for this function

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $iWidth = $iHeight = 200; // desired image result dimensions
        $iJpgQuality = 90;

        if ($_FILES) {

            // if no errors and size less than 1000kb
            if (! $_FILES['image_file']['error'] && $_FILES['image_file']['size'] < 1000 * 1024) {
                if (is_uploaded_file($_FILES['image_file']['tmp_name'])) {

                    // new unique filename
                    $sTempFileName = $thumb_dir .$u;

                    // move uploaded file into cache folder
                    move_uploaded_file($_FILES['image_file']['tmp_name'], $sTempFileName);

                    // change file permission to 644
                    @chmod($sTempFileName, 0644);

                    if (file_exists($sTempFileName) && filesize($sTempFileName) > 0) {
                        $aSize = getimagesize($sTempFileName); // try to obtain image info
                        if (!$aSize) {
                            @unlink($sTempFileName);
                            return;
                        }

                        // check for image type
                        switch($aSize[2]) {
                            case IMAGETYPE_JPEG:
                                $sExt = '.jpg';

                                // create a new image from file 
                                $vImg = @imagecreatefromjpeg($sTempFileName);
                                break;
                            /*case IMAGETYPE_GIF:
                                $sExt = '.gif';

                                // create a new image from file 
                                $vImg = @imagecreatefromgif($sTempFileName);
                                break;*/
                            case IMAGETYPE_PNG:
                                $sExt = '.png';

                                // create a new image from file 
                                $vImg = @imagecreatefrompng($sTempFileName);
                                break;
                            default:
                                @unlink($sTempFileName);
                                return;
                        }

                        // create a new true color image
                        $vDstImg = @imagecreatetruecolor( $iWidth, $iHeight );

                        // copy and resize part of an image with resampling
                        imagecopyresampled($vDstImg, $vImg, 0, 0, (int)$_POST['x1'], (int)$_POST['y1'], $iWidth, $iHeight, 90, 90);

                        // define a result image filename
                        $sResultFileName = $sTempFileName . $sExt;

                        // output image to file
                        imagejpeg($vDstImg, $sResultFileName, $iJpgQuality);
                        @unlink($sTempFileName);

                        return $sResultFileName;
                    }
                }
            }
        }
    }
}
	
	    /**
     * Log in method
     *
     * @return boolean    TRUE on success and FALSE on failure
     */
	 
	public function getUserThumb($u) {
		$sql = "SELECT UserThumb
                FROM users
                WHERE UserEmail=:email
                LIMIT 1";
		try {
			 $stmt = $this->_db->prepare($sql);
             $stmt->bindParam(':email', $u, PDO::PARAM_STR);
			 $stmt->execute();
			 $row = $stmt->fetch();
			 
			echo '<img src='.$row['UserThumb'].' class="user_thumb"></img>';
			}
		catch(PDOException $e)
        {
            return FALSE;
        }
	
	}
    public function accountLogin()
    {
        $sql = "SELECT UserEmail, FirstName, LastName, user_dir, UserThumb, UserName, UserID 
                FROM users
                WHERE UserEmail=:email
                AND Password=MD5(:pass)
                LIMIT 1";
        try
        {
            $stmt = $this->_db->prepare($sql);
            $stmt->bindParam(':email', $_POST['email'], PDO::PARAM_STR);
            $stmt->bindParam(':pass', $_POST['password'], PDO::PARAM_STR);
            $stmt->execute();
            if($stmt->rowCount()==1)
            {
				$row = $stmt->fetch();
                $_SESSION['Username'] = htmlentities($_POST['email'], ENT_QUOTES);
                $_SESSION['LoggedIn'] = 1;
				$_SESSION['UserThumb'] = $row['UserThumb'];
				$_SESSION['UserID'] = $row['UserName'];
				$_SESSION['ID'] = $row['UserID'];
				$_SESSION['FirstName'] = $row['FirstName'];
				$_SESSION['LastName'] = $row['LastName'];
				$_SESSION['home_dir'] = $row['user_dir'];
                return TRUE;
            }
            else
            {
                return FALSE;
            }
        }
        catch(PDOException $e)
        {
            return FALSE;
        }
    }


}


?>